// 正式
// const baseDomain = "https://dev-api.lefujin.cn/";
// 测试
// const baseDomain = "https://api.lefujin.cn/";
// 临时
const baseDomain = "http://dev-api2.lefujin.cn/";
const baseUrl = baseDomain + "api/";
var timestamp = Date.parse(new Date()) / 1000
import md5 from 'js-md5'
let Base64 = require('js-base64').Base64
import getServerNo from '../common/js/appUpdate.js'
import $util from './util.js'

/**
 * 生成请求签名
 */
function createSign() {
	timestamp = Date.parse(new Date()) / 1000
	let last_num = timestamp.toString().slice(-1)
	if (last_num <= 3) {
		last_num = 3;
	} else if (last_num > 3 && last_num <= 6) {
		last_num = 6;
	} else if (last_num > 6 && last_num <= 9) {
		last_num = 9;
	} else {
		last_num = 0;
	}
	let new_str = timestamp.toString().slice(0, 9)
	let md5_str = md5(new_str);
	let str_split = md5_str.split('')
	let new_str_split = str_split.sort()
	return Base64.encode(new_str_split.join("") + '&time=' + timestamp);
}

const httpRequest = (opts, data) => {
	let numMath = Math.ceil(Math.random() * 10000);
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			'sign': createSign(),
			"Content-Type": "application/json; charset=UTF-8",
			'cid': uni.getStorageSync('cid') || numMath
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'sign': createSign(),
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
			'cid': uni.getStorageSync('cid') || numMath
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				if (res.data.code == 8100 || res.data.code == 8000) {
					uni.showToast({
						icon: 'none',
						title: '登录过期，请重新登录',
						position: 'bottom'
					})
					uni.removeStorage({
						key: 'token',
						success: function(res) {}
					});
				} else {
					resolve(res.data)
				}
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};

var token = '';
let isRefreshing = 0
let isLoginshow = false
//带Token请求
const httpTokenRequest = (opts, data) => {
	try {
		token = uni.getStorageSync('token');
	} catch (e) {
		// error
	}
	let numMath = Math.ceil(Math.random() * 10000);
	// console.log(opts,opts.url,'xiaopts')
	//此token是登录成功后后台返回保存在storage中的
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			'token': token,
			'sign': createSign(),
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8",
			'cid': uni.getStorageSync('cid') || numMath
		} : {
			'token': token,
			'sign': createSign(),
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
			'cid': uni.getStorageSync('cid') || numMath
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				if (res.data.code == 8100 || res.data.code == 8000) {
					if (isLoginshow) {
						return
					} else {
						isLoginshow = true
						uni.removeStorage({
							key: 'token',
							success: function(res) {}
						});
						// #ifdef APP
						if ($util.phoneType() == 'android') {
							var obj = {
								versionCode: "1.0.1",
								versionName: "101",
								versionInfo: "asas",
								updateType: "forcibly",
								downloadUrl: ""
							}
							getServerNo.updatePopup(obj, () => {
								isLoginshow = false
								uni.navigateTo({
									url: '/pages/register/register'
								})
							})
						} else {
							uni.showModal({
								title: '提示',
								content: '登录过期，请重新登录',
								success: function(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: '/pages/register/register'
										})
									} else if (res.cancel) {
										isLoginshow = false
									}
								},
							});
						}
						// #endif
						// #ifndef APP
						uni.showModal({
							title: '提示',
							content: '登录过期，请重新登录',
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/register/register'
									})
								} else if (res.cancel) {
									isLoginshow = false
								}
							}
						});
						// #endif
					}
				} else {
					isLoginshow = false
					resolve(res.data)
				}
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};




export default {
	httpRequest,
	baseUrl,
	baseDomain,
	httpTokenRequest,
}